package com.itheima.reggie.handler;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.resp.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice()
@Slf4j
//全局异常处理
public class GlobalExceptionHandler {
    //异常处理方法 sql索引唯一异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage());//打印异常信息
        if (e.getMessage().contains("Duplicate entry")) {//违反username唯一约束
            //username已存在
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    //自定义异常处理
    @ExceptionHandler(CustomException.class)
    public R exceptionHandler(CustomException ce) {
        log.info(ce.getMessage());//打印异常信息
        return R.error(ce.getMessage());
    }

}
